package gridfs.dao;

import com.mongodb.client.MongoCollection;
import org.bson.BsonDateTime;
import org.bson.Document;
import org.bson.types.ObjectId;

import java.io.InputStream;

final class GridFileCreate {
    private final MongoCollection<Document> filesCollection;
    private final MongoCollection<Document> chunkCollection;
    private final int chunkSize;

    GridFileCreate(MongoCollection<Document> filesCollection, MongoCollection<Document> chunkCollection, int chunkSize) {
        this.filesCollection = filesCollection;
        this.chunkCollection = chunkCollection;
        this.chunkSize = chunkSize;
    }


    void exec(ObjectId id, String filename, String dirname, long size, Document metadata) {
        createFile(id, filename, dirname, size, metadata);
    }

    private void createFile(ObjectId id, String filename, String dirname, long size, Document metadata) {
        Document fileDocument = new Document("_id", id)
                .append("length", size)
                .append("chunkSize", chunkSize)
                .append("uploadDate", new BsonDateTime(System.currentTimeMillis()))
                .append("dirname", dirname)
                .append("filename", filename);
        if (null != metadata && !metadata.isEmpty()) {
            fileDocument.append("metadata", metadata);
        }
        filesCollection.insertOne(fileDocument);
    }
}
